import UIManager from '../../UI/UIManager';
import QGame from '../../Tools/QGame';
import Character from '../Basis/Character';
import { PlotType, PlotCharacterMove, DialogDat, DialogType } from '../../Tools/QType';

const {ccclass, property} = cc._decorator;

/**
 * 每个场景的设计
 */
@ccclass
export default class Screen extends cc.Component {
    protected UIManager:UIManager;
    protected QGame:QGame;
    get MapState(){
        return this.QGame.Map.getState();
    }

    /**
     * 第一次进入场景事件
     */
    public firstEnterDat=[];

    /**
     * 当前并行执行的事件数组
     */
    private currentEvents=[];
    /**
     * 当前并行执行的事件Index
     */
    private currentEventIndex:number=0;
    onLoad(){        
        this.UIManager = this.node.getChildByName("UI").getComponent(UIManager);
        this.QGame = QGame.Instance;
        this.MapState.enter++;
        
        this.node.on("DialogEnd",this.nextEvent,this);    
        this.node.on("AutoMoveEnd",this.nextEvent,this);
        /** 监听事件转发 */
        this.node.on("EventForWard",this.EventForWard,this);
       

    }
    
    start(){
    
        let showCityName:DialogDat = 
        {
                type:DialogType.City,
                content:"杭州城"
        }                   
        this.UIManager.openDialog(showCityName)  
     
        this.firstEnter();
    }


    /**
     * 第一次进入场景
     */
    firstEnter(){
        if(this.MapState.enter!=1||!this.firstEnterDat.length)return;
        this.currentEvents = this.firstEnterDat;
        this.currentEventIndex=0;       
    }
    
    /**
     * 执行下一个事件
     */
    nextEvent(){        
        if(this.currentEventIndex<this.currentEvents.length){
            this.runEvent();
        }else{
            //一串并行事件执行完成
            this.currentEvents = [];
            this.currentEventIndex=0;            
        }
    }
    /**
     * 执行事件
     */
    runEvent(){
        let obj = this.currentEvents[this.currentEventIndex];        
        cc.log(obj);
        switch(obj.type){         
            case PlotType.Move:
            case PlotType[PlotType.Move]:
                let dat = obj.data as PlotCharacterMove;                                        
                let ch = this.node.getChildByName("MapBg").getChildByName(dat.name).getComponent(Character);
                ch.AutoMove(dat.to);
            break;
            case PlotType.Dialog:
            case PlotType[PlotType.Dialog]:
                this.UIManager.openDialog(obj.data as DialogDat)    
            break;
        }
        this.currentEventIndex++;
    }

    /**
     * 事件转发
     */
    EventForWard(event:cc.Event.EventCustom){        
        let dat = event.getUserData();
        this.currentEvents = dat;
        this.currentEventIndex = 0;
        this.nextEvent();
    }
}
